package com.example.myui.adapter;

import android.content.Context;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myui.R;
import com.example.myui.model.ApkModel;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.security.spec.PSSParameterSpec;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/25/025.
 */

public class DownLoadAdapter extends RecyclerView.Adapter<DownLoadAdapter.Holder> {
    private final NumberFormat numberFormat;
    private List<ApkModel> apkModels;
    private Context mContext;
    private String TAG = DownLoadAdapter.class.getSimpleName();
    private DownloadTask task;
    private int type;
    private List<DownloadTask> tasks = new ArrayList<>();

    public static final int TYPE_ALL = 0;
    public static final int TYPE_FINISH = 1;
    public static final int TYPE_ING = 2;


    public DownLoadAdapter(Context context, List<ApkModel> apks) {
        this.mContext = context;
        this.apkModels = apks;
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
    }

    //    public void updateData(int type) {
//        //这里是将数据库的数据恢复
//        this.type = type;
//        if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll());
//        if (type == TYPE_FINISH)
//            values = OkDownload.restore(DownloadManager.getInstance().getFinished());
//        if (type == TYPE_ING)
//            values = OkDownload.restore(DownloadManager.getInstance().getDownloading());
//        notifyDataSetChanged();
//    }
    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.item_down_apk, parent, false);
        Holder holder = new Holder(inflate);
        return holder;
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        Glide.with(mContext)
                .load(apkModels.get(position).iconUrl)
                .into(holder.icon);

        holder.name.setText(apkModels.get(position).name);
        holder.start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从数据库中恢复数据
                List<Progress> progressList = DownloadManager.getInstance().getAll();
                List<DownloadTask> restore = OkDownload.restore(progressList);
                for (int i = 0; i < progressList.size(); i++) {
                    Log.i(TAG, "onClick: " + progressList.get(i).filePath);
                }

                Log.i(TAG, "size ==: " + progressList.size());
                for (int i = 0; i < progressList.size(); i++) {
                    String tag = progressList.get(i).tag;
                    Log.i(TAG, "==" + i + "==" + tag + "///////////////Size :");
                }
//                DownloadTask task = values.get(position);
                GetRequest<File> file = OkGo.<File>get(apkModels.get(position).url);

                DownloadTask task = OkDownload.request(apkModels.get(position).url, file)
                        .folder(Environment.getExternalStorageDirectory() + "/apkdown")
                        .fileName(apkModels.get(position).name + ".apk")
                        .save()
                        .register(new DownloadListener(position + "") {
                            @Override
                            public void onStart(Progress progress) {
                                Log.i(TAG, "onStart: " + progress.status);
                                if (progress.status == Progress.ERROR) {
                                    restore.get(position).remove(true);
                                }
                            }

                            @Override
                            public void onProgress(Progress progress) {
                                holder.progress.setText(numberFormat.format(progress.fraction));
                                String speed = Formatter.formatFileSize(mContext, progress.speed);
                                holder.speed.setText(String.format("%s/s", speed));
                                holder.size.setText((int) (progress.totalSize / 1024 / 1024) + "");
                            }

                            @Override
                            public void onError(Progress progress) {
                                Toast.makeText(mContext, "errot:" + progress.status, Toast.LENGTH_SHORT).show();
                                Log.i(TAG, "onError: " + progress.status + "------------->");
                            }

                            @Override
                            public void onFinish(File file, Progress progress) {
                                Toast.makeText(mContext, "onFinisd:" + progress.status, Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onRemove(Progress progress) {

                            }
                        });

                tasks.add(task);
                task.start();
//                        .start();
            }
        });

        holder.pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //暂停下载
//                if (null != onPauseButtonClick) {
//                    onPauseButtonClick.onPauseClick(apkModels.get(position), position);
//                }


                if (OkDownload.getInstance().hasTask(apkModels.get(position).url)) {
                    task = OkDownload.getInstance().getTask(apkModels.get(position).url)
                            .register(new DesListener(holder, position + ""));
                }


                if (task != null) {
                    task.pause();
                    refreshUI(holder, task.progress);
                }
            }
        });

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tasks.get(position).remove(true);
            }
        });
        holder.restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tasks.get(position).restart();
            }
        });
        holder.deleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private onStartButtonClick onStartButtonClick;
    private onPauseButtonClick onPauseButtonClick;

    public void setOnStartButtonClick(DownLoadAdapter.onStartButtonClick onStartButtonClick) {
        this.onStartButtonClick = onStartButtonClick;
    }

    public void setOnPauseButtonClick(DownLoadAdapter.onPauseButtonClick onPauseButtonClick) {
        this.onPauseButtonClick = onPauseButtonClick;
    }

    public void unRegister() {
        Map<String, DownloadTask> taskMap = OkDownload.getInstance().getTaskMap();
        for (DownloadTask task : taskMap.values()) {
            task.unRegister(createTag(task));
        }
    }

    private String createTag(DownloadTask task) {
        return type + "_" + task.progress.tag;
    }

    public interface onStartButtonClick {
        void onStartClick(ApkModel apkModel, int position);
    }

    public interface onPauseButtonClick {
        void onPauseClick(ApkModel apkModel, int position);
    }

    @Override
    public int getItemCount() {
        return apkModels.size();
    }

    public class Holder extends RecyclerView.ViewHolder {
        private ImageView icon;
        private TextView name;
        private TextView size;
        private TextView speed;
        private TextView progress;
        private Button start;
        private Button pause;
        private Button delete;
        private Button deleteAll;
        private Button restart;


        public Holder(View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.iv_icon);
            name = itemView.findViewById(R.id.tv_name);
            size = itemView.findViewById(R.id.tv_size);
            speed = itemView.findViewById(R.id.tv_speed);
            start = itemView.findViewById(R.id.btn_start);
            pause = itemView.findViewById(R.id.btn_pause);
            progress = itemView.findViewById(R.id.tv_progress);
            delete = itemView.findViewById(R.id.btn_clear);
            deleteAll = itemView.findViewById(R.id.btn_clearall);
            restart = itemView.findViewById(R.id.button2);
        }
    }

    private class DesListener extends DownloadListener {
        private Holder mHolder;

        public DesListener(Holder holder, Object tag) {
            super(tag);
            this.mHolder = holder;
        }

        @Override
        public void onStart(Progress progress) {

        }

        @Override
        public void onProgress(Progress progress) {
            refreshUI(mHolder, progress);
        }

        @Override
        public void onError(Progress progress) {

        }

        @Override
        public void onFinish(File file, Progress progress) {

        }

        @Override
        public void onRemove(Progress progress) {

        }
    }

    private void refreshUI(Holder mHolder, Progress progress) {
        String currentSize = Formatter.formatFileSize(mContext, progress.currentSize);
        String totalSize = Formatter.formatFileSize(mContext, progress.totalSize);
//        mHolder.progress.setText(currentSize + "/" + totalSize);
        String speed = Formatter.formatFileSize(mContext, progress.speed);
        mHolder.speed.setText(String.format("%s/s", speed));
        mHolder.progress.setText(numberFormat.format(progress.fraction));
//        pbProgress.setMax(10000);
//        pbProgress.setProgress((int) (progress.fraction * 10000));
        switch (progress.status) {
//            case Progress.NONE:
//                download.setText("下载");
//                break;
//            case Progress.LOADING:
//                download.setText("暂停");
//                break;
//            case Progress.PAUSE:
//                download.setText("继续");
//                break;
//            case Progress.WAITING:
//                download.setText("等待");
//                break;
//            case Progress.ERROR:
//                download.setText("出错");
//                break;
//            case Progress.FINISH:
//                if (ApkUtils.isAvailable(mContext, new File(progress.filePath))) {
//                    download.setText("卸载");
//                } else {
//                    download.setText("安装");
//                }
//                break;
        }
    }
}
